"""
通用工具函数
"""

def format_uptime(days: int, hours: int) -> str:
    """格式化运行时间"""
    if days > 0:
        return f"{days}天{hours}小时"
    else:
        return f"{hours}小时"

def calculate_percentage(value: int, total: int) -> float:
    """计算百分比"""
    if total == 0:
        return 0.0
    return round((value / total) * 100, 2)

def filter_by_status(items: list, status: str) -> list:
    """根据状态过滤项目"""
    return [item for item in items if item.get('status') == status]

def sort_by_field(items: list, field: str, reverse: bool = False) -> list:
    """根据字段排序"""
    return sorted(items, key=lambda x: x.get(field, 0), reverse=reverse)


def timestamp_to_datetime(millisecond_timestamp):
    from datetime import datetime
    """将13位毫秒时间戳转换为datetime对象[1,6](@ref)"""
    # 将毫秒转换为秒（除以1000.0以保持精度）
    second_timestamp = millisecond_timestamp / 1000.0
    # 转换为datetime对象
    dt_object = datetime.fromtimestamp(second_timestamp)
    return dt_object

from datetime import datetime

def datetime_to_timestamp(dt_obj):
    """将datetime对象转换为13位毫秒时间戳[4,10](@ref)"""
    # 获取秒级时间戳（浮点数），然后乘以1000得到毫秒，最后取整
    millisecond_timestamp = int(dt_obj.timestamp() * 1000)
    return millisecond_timestamp
